package dyyx.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Random;

import dyyx.DataGen;
import dyyx.util.CommUtil;
import dyyx.util.JdbcUtil;

public class BatchInsertTest {
	
	private static final Random rand = new Random();

	public static void main(String[] args) throws Exception {
		
		System.out.println("hello,BatchInsertTest,"+new Date());	
		
		Connection cn = JdbcUtil.getConn();		
		// autoCommit false
		System.out.println("cn="+cn+",autoCommit="+cn.getAutoCommit());	
		// id UInt32,col1 String,col2 String,create_date date
		
		String sqlcount = "select count(*) from test01";
		
		String count0 = JdbcUtil.queryAsString(cn, sqlcount);

		
		String sql = "insert into test01(id,col1,col2,create_date) values(?,?,?,?)";
		int num = 100;

		System.out.println("batch insert num "+num);
		
		PreparedStatement pstmt = null;
		pstmt = cn.prepareStatement(sql);
		
		for(int i=0;i<num;i++){
			pstmt.setInt(1, genId());
			String create_date = genCreateDate();
			String col1 = "col1_"+create_date+"_"+LocalDateTime.now();
			String col2 = "col2_"+create_date+"_"+LocalDateTime.now();
			pstmt.setString(2, col1);
			pstmt.setString(3, col2);
			pstmt.setString(4,create_date);

			pstmt.addBatch();

		}
		pstmt.executeBatch();
		
		String count1 = JdbcUtil.queryAsString(cn, sqlcount);

		
		JdbcUtil.close(cn);
		
		System.out.println("batch insert done,num = "+num);	
		
		System.out.println("count0="+count0+",count1="+count1);	

	
	}
	
	
	private static int genId(){
		int tmp = rand.nextInt(30);
		if(tmp<=0){
			tmp = 1;
		}
		return tmp;  
	}
	
	private static String genCreateDate(){
		Date date = DataGen.genTradeTime();
		return CommUtil.getDateString(date);
	}
}
